#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

void* func(void*);

int main(int argc,char* argv[])
{
  pthread_t tid;
  int tcp_fd = socket(AF_INET,SOCK_STREAM,0);
  if(tcp_fd == -1)
  {
    perror("socket fail");
    return -1;
  }

  struct sockaddr_in server_addr;
  server_addr.sin_port = htons(50000);
  server_addr.sin_family = AF_INET;
  inet_pton(AF_INET,"127.0.0.1",&server_addr.sin_addr);
  
  int num_1 = 10;
  setsockopt(tcp_fd,SOL_SOCKET,SO_SNDLOWAT,&num_1,10);

  int ret = connect(tcp_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
  if(ret < 0)
  {
    printf("server is close\n");
    return -1;
  }

  pthread_create(&tid,NULL,func,(void*)&tcp_fd);
  char buf[1024] = {0};
  size_t num = 1024;
  while(1)
  {

    memset(buf,0,1024);
    fgets(buf,1024,stdin);
    buf[strcspn(buf, "\n")] = 0;
    send(tcp_fd,buf,strlen(buf),0);
    if(!strcmp(buf,"bye"))
      break;
  }


  close(tcp_fd);
  return 0;
}

void* func(void* argv)
{
    int tcp_fd = *(int*)argv;
    char buf[1024];
    while(1)
    {
        recv(tcp_fd,buf,1024,0);
        if(!strcmp(buf,"client close"))
        {
          printf("%s\n",buf);
          close(tcp_fd);
          exit(-1);
        }
    }

    pthread_exit(NULL);
}
